<template>
  <view class="apply-v">
    <view class="top_sticky">
      <view
        style="position: absolute; left: 20rpx; font-size: 36rpx"
        @click="goBack()"
        ><u-icon name="arrow-left"></u-icon
      ></view>
      考勤详情
    </view>
    <view class="" style="height: 40vh">
      <map
        id="myMap"
        :style="{ width: '100%', height: '100%' }"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :show-location="true"
        :enable-scroll="true"
        :enable-zoom="true"
        :enable-overlooking="false"
        :enable-building="true"
        :enable-rotate="false"
        :show-compass="true"
        :show-scale="true"
        :subkey="amapKey"
        @markertap="onMarkerTap"
        @tap="onMapTap"
        @regionchange="onRegionChange"
      ></map>
    </view>

    <view style="height: 40vh">
      <view class="popup-content">
        <view class="popup-header">
          <view class="drag-handle"></view>
        </view>
        <view class="popup-body">
          <view class="form-item">
            <text>考勤时间</text>
            <u-input
              type="text"
              v-model="info.jobinfo.attendanceTime"
              placeholder=""
              disabled
              placeholder-style="color: #1F2329"
            />
          </view>
          <view class="divider"></view>
          <view class="form-item">
            <text>考勤位置</text>
            <u-input
              type="text"
              v-model="reportRemark"
              placeholder=""
              disabled
              placeholder-style="color: #1F2329"
            />
          </view>
          <view class="divider"></view>
          <view class="location-info">
            <view
              style="
                width: 100%;
                font-size: 32rpx;
                background-color: #fdf6ec;
                color: #ff9900;
                padding: 15rpx 25rpx;
                align-items: center;
                border-radius: 3px;
                display: inline-block;
                border: 1px solid #fcbd71;
                line-height: 1;
              "
              ><u-icon name="map-fill"></u-icon>位置：{{
                info.jobinfo.notes
              }}</view
            >
          </view>

          <!-- 添加图片上传组件 -->
          <view class="upload-section">
            <text
              style="
                margin-bottom: 10rpx;
                display: inline-block;
                color: #8f959e;
                font-size: 32rpx;
              "
              >上传照片</text
            >
            <!-- 当isattendance不是'是'时才允许上传 -->
            <wpwork-upload
              v-model="info.imageurl"
              :limit="9"
              tipText=""
              :disabled="info.jobinfo.isattendance === '是'"
            ></wpwork-upload>

            <!-- 当isattendance不是'是'时才显示打卡按钮 -->
            <button
              v-if="info.jobinfo.isattendance !== '是'"
              type="primary"
              class="button-btn"
              style="width: 100%"
              @click="submitReport"
            >
              打卡
            </button>

            <!-- 当已经打卡时显示提示信息 -->
            <view
              v-else
              class="打卡提示"
              style="
                text-align: center;
                padding: 20rpx;
                color: #666;
                background-color: #f5f5f5;
                border-radius: 10rpx;
                margin-top: 20rpx;
              "
            >
              <u-icon
                name="checkmark-circle"
                color="#07c160"
                size="36rpx"
              ></u-icon>
              <text style="margin-left: 10rpx">已完成打卡</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
// 导入平台判断工具
const platform = uni.getSystemInfoSync().platform;
// 导入图片上传组件
import wpworkUpload from "@/components/wpwork/wpwork-upload/index.vue";
import { updateData } from "@/api/xjxt.js";
// 高德地图配置项
const mapConfig = {
  key: "094537be8ea85f6f11c94e5f8c080da5",
  version: "2.0",
  plugins: ["AMap.Scale", "AMap.Geolocation"],
  AMapUI: {
    version: "1.1",
    plugins: [1],
  },
  Loca: {
    version: "2.0.0",
  },
};

export default {
  components: {
    wpworkUpload,
  },
  data() {
    return {
      height: "1450rpx",
      showPopup: true,
      reportName: "",
      reportRemark: "",
      location: "福建省福州市鼓楼区凉州路",
      // 高德地图配置
      mapConfig: mapConfig,
      // 使用配置中的key
      amapKey: mapConfig.key,
      // 武汉市中心经纬度
      latitude: 30.5928,
      longitude: 114.3055,
      currentLocation: "湖北省武汉市江汉区",
      // 标记点配置
      markers: [
        {
          id: 1,
          latitude: 30.5928,
          longitude: 114.3055,
          width: platform === "devtools" ? 40 : 30,
          height: platform === "devtools" ? 40 : 30,
          // 使用水滴形状的标记点
          iconPath: "/static/image/mark.png", // 项目中已有的图标
          callout: {
            content: "考勤点",
            display: "BYCLICK",
            color: "#ffffff",
            bgColor: "#014FEB",
            padding: 10,
            borderRadius: 5,
          },
        },
      ],
      info: {
        imageurl: [], // 初始化图片上传字段
      },
      // 地图上下文
      mapContext: null,
      // H5环境下的地图实例
      h5MapInstance: null,
      // H5环境下的地图标记点引用
      h5MapMarkers: [],
      // 弹窗显示状态，设置为true使其默认打开
    };
  },
  computed: {},
  watch: {},
  onShow() {
    this.showPopup = true;
  },
  onLoad(query) {
    if (query.data) {
      const data = JSON.parse(decodeURIComponent(query.data));
      this.info = data;
      // 确保imageurl字段存在并正确处理JSON字符串
      if (!this.info.imageurl) {
        this.info.imageurl = [];
      } else if (typeof this.info.imageurl === "string") {
        try {
          // 如果是字符串尝试解析为数组
          this.info.imageurl = JSON.parse(this.info.imageurl);
        } catch (e) {
          // 解析失败则重置为空数组
          this.info.imageurl = [];
        }
      }
      this.reportRemark = "此位置" + data.jobinfo.distance + "米内";
      if (this.info.jobinfo.attendanceTime == "") {
        this.info.jobinfo.attendanceTime = this.wpwork.toDate(
          Date.now(),
          "yyyy-MM-dd HH:mm:ss"
        );
      }

      // 从info.location中提取经纬度，使用逗号分隔数值
      if (this.info.location) {
        try {
          const locationArr = this.info.location.split(",");
          if (locationArr.length >= 2) {
            // 假设格式为"longitude,latitude"
            this.longitude = parseFloat(locationArr[0]);
            this.latitude = parseFloat(locationArr[1]);

            // 同时更新标记点的经纬度
            if (this.markers && this.markers.length > 0) {
              this.markers[0].longitude = this.longitude;
              this.markers[0].latitude = this.latitude;
            }

            // 如果是H5环境且地图已经初始化，更新地图显示
            if (platform === "h5" && this.h5MapInstance) {
              this.updateH5MapPosition();
            }
          }
        } catch (e) {
          console.error("解析经纬度失败:", e);
        }
      }
    }
  },
  onReady() {
    // 页面渲染完成后，可以获取地图实例
    if (platform === "h5") {
      // H5平台下，需要等待DOM加载完成后初始化高德地图
      this.initH5Map();
    } else {
      // 微信小程序等平台
      this.mapContext = wx.createMapContext("myMap");
    }
  },
  methods: {
    // H5环境下初始化高德地图
    initH5Map() {
      // 检查是否在H5环境且已加载高德地图API
      if (window.AMap && this.mapConfig) {
        // 获取地图容器
        const mapContainer = document.getElementById("myMap");
        if (mapContainer) {
          // 创建地图实例
          this.h5MapInstance = new window.AMap.Map(mapContainer, {
            resizeEnable: true,
            zoom: 16,
            center: [this.longitude, this.latitude],
            dragEnable: true,
            zoomEnable: true,
          });

          // 加载插件
          if (this.mapConfig.plugins && this.mapConfig.plugins.length > 0) {
            this.h5MapInstance.plugin(this.mapConfig.plugins, () => {
              // 添加比例尺控件
              if (this.mapConfig.plugins.includes("AMap.Scale")) {
                const scale = new window.AMap.Scale();
                this.h5MapInstance.addControl(scale);
              }

              // 添加定位控件
              if (this.mapConfig.plugins.includes("AMap.Geolocation")) {
                const geolocation = new window.AMap.Geolocation({
                  enableHighAccuracy: true,
                  timeout: 10000,
                  buttonPosition: "RB",
                  buttonOffset: new window.AMap.Pixel(10, 20),
                  zoomToAccuracy: true,
                });
                this.h5MapInstance.addControl(geolocation);

                // 绑定定位事件
                geolocation.getCurrentPosition();
                window.AMap.event.addListener(
                  geolocation,
                  "complete",
                  (data) => {
                    console.log("定位成功:", data);
                    this.latitude = data.position.lat;
                    this.longitude = data.position.lng;
                  }
                );
                window.AMap.event.addListener(geolocation, "error", (data) => {
                  console.log("定位失败:", data);
                });
              }
            });
          }

          // 加载AMapUI
          if (this.mapConfig.AMapUI && window.AMapUI) {
            // 这里可以添加AMapUI相关功能
          }

          // 加载Loca
          if (this.mapConfig.Loca && window.Loca) {
            // 这里可以添加Loca相关功能
          }

          // 添加标记点
          this.addMarkersToH5Map();
        }
      }
    },

    // 向H5地图添加标记点
    addMarkersToH5Map() {
      if (this.h5MapInstance && this.markers && this.markers.length > 0) {
        // 移除已有的标记点
        this.h5MapInstance.remove(this.h5MapMarkers || []);
        this.h5MapMarkers = [];

        const markerList = this.markers.map((marker) => {
          const amapMarker = new window.AMap.Marker({
            position: [marker.longitude, marker.latitude],
            icon: {
              size: new window.AMap.Size(marker.width, marker.height),
              image: marker.iconPath,
            },
            title: marker.callout?.content || "",
          });

          // 添加点击事件
          amapMarker.on("click", () => {
            this.onMarkerTap({
              markerId: marker.id,
            });
          });

          this.h5MapMarkers.push(amapMarker);
          return amapMarker;
        });

        this.h5MapInstance.add(markerList);
      }
    },

    // 更新H5地图中心点和标记点
    updateH5MapPosition() {
      if (this.h5MapInstance) {
        // 设置地图中心点
        this.h5MapInstance.setCenter([this.longitude, this.latitude]);
        // 更新标记点
        this.addMarkersToH5Map();
      }
    },
    // 生命周期方法
    onUnload() {},
    openPopup() {
      this.showPopup = true;
    },
    submitReport() {
      // 处理上报逻辑
      // 深拷贝info对象
      this.info.jobinfo.isattendance = "是";
      this.info.jobinfo = JSON.stringify(this.info.jobinfo);
      const submitData = JSON.parse(JSON.stringify(this.info));

      // 将imageurl数组转换为JSON字符串
      if (Array.isArray(submitData.imageurl)) {
        submitData.imageurl = JSON.stringify(submitData.imageurl);
      }

      console.log("提交的数据:", submitData);
      updateData(submitData).then((res) => {
        // 显示保存成功提示
        uni.showToast({
          title: "保存成功",
          icon: "success",
          duration: 2000,
          complete: () => {
            // 保存成功后返回上一页
            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          },
        });
      });
      // 关闭弹出框
      this.showPopup = false;
    },
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },
    // 地图标记点点击事件
    onMarkerTap(e) {
      console.log("点击了标记点:", e);
    },
    // 地图点击事件
    onMapTap(e) {
      console.log("点击了地图:", e);
    },
    // 地图区域变化事件
    onRegionChange(e) {
      // 拖动结束时获取中心点位置
      if (e.type === "end" && e.causedBy === "drag") {
        this.mapCtx.getCenterLocation({
          success: (res) => {
            // 这里可以根据经纬度调用逆地理编码API获取详细地址
            console.log("当前地图中心位置:", res);
          },
        });
      }
    },
  },
};
</script>

<style lang="scss">
.top_sticky {
  z-index: 999;
  position: sticky;
  top: var(--window-top);
  background: linear-gradient(to right, #014feb, #2775fe);
  height: 130rpx;
  line-height: 170rpx;
  color: #fff;
  text-align: center;
  font-weight: 400;
  font-size: 36rpx;
}

.popup-content {
  background-color: #fff;
  padding-top: 15rpx;
  padding-left: 35rpx;
  padding-right: 35rpx;
  padding-bottom: 45rpx;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}

.popup-header {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.drag-handle {
  width: 70px;
  height: 5px;
  background-color: #ccc;
  border-radius: 5px;
}

.popup-body {
  display: flex;
  flex-direction: column;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.form-item text {
  width: 80px;
  color: #8f959e;
  font-size: 32rpx;
}

.location-info {
  margin-bottom: 20rpx;
}

// 上传组件样式
.upload-section {
  margin-bottom: 20rpx;
}

.button-btn {
  height: 78rpx;
  border-radius: 50rpx;
  font-size: 30rpx;
}

.divider {
  border-bottom: 1px solid #ebf5ff;
  margin-bottom: 20rpx;
}

/deep/ .u-input__input {
  font-size: 32rpx !important;
}

/deep/ .uni-input-wrapper {
  color: #1f2329 !important;
}
</style>
